import { extendApi } from '@inbiz/utils';
import { MutableRefObject } from 'react';
import { ecmSearchTypeField } from '../../store/hooks/useJumpResult';
import { StateType } from '../../store/searchPropsContext';

export default extendApi(
  (
    _,
    props: StateType,
    {
      updateState: $uiState, 
      jumpResultRef, 
      saveSearchData,
      ...rest
    }
  ) => {
    return {
      search: (data: {
        guid: string;
        documentType?: 'file' | 'folder'; // IndexName  为_document_时有效，
        fileFields: ('filecontent' | 'filename' | 'filetag')[]; // 文件索引库搜索字段， documentType 为 file时生效
        keyword?: string;
        isFuzzySearch?: boolean; //精确搜索。还是模糊搜索
      }) => {
        if (!data?.guid) {
          console.log('guid不能为空');
          return;
        }

        const tabsConfig = props.tabsConfig;
        const selectShowTab = tabsConfig.find((item) => item.guid === data.guid);
        if (selectShowTab) {
          const newData = {
            selectShowTab,
            keyword: data.keyword,
            isFuzzySearch: data.isFuzzySearch,
            visibleDrawer: false,
            switchAdSearch: false,
            showSearchResultPanel: false,
            ecmSearchType: [] as number[],
          };
          if (selectShowTab.isDMS) {
            if (data.documentType === 'folder') {
              newData.ecmSearchType = [4];
            } else {
              newData.ecmSearchType = data.fileFields?.map((item) => ecmSearchTypeField[item]);
            }
          }
          $uiState(newData);

          setTimeout(() => {
            jumpResultRef.current(data.keyword);
          }, 0);
        }
      },
      fillValue: saveSearchData,
      ...rest
    };
  },
);
